package com.chushouya.product.service.admin.impl;

import com.chushouya.product.dto.admin.attribute.*;
import com.general.framework.core.lang.Beans;
import com.general.framework.core.lang.Check;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.schema.PageResult;
import com.chushouya.product.dao.entity.AttributeItemEntity;
import com.chushouya.product.dao.entity.AttributeItemValueEntity;
import com.chushouya.product.dao.repository.AttributeItemRepository;
import com.chushouya.product.dao.repository.AttributeItemValueRepository;
//=====product.dto.admin.attribute.*;
import com.chushouya.product.dto.admin.attribute.*;
import com.chushouya.product.service.admin.AttributeItemValueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AttributeItemValueServiceImpl implements AttributeItemValueService {

    @Resource
    private AttributeItemValueRepository attributeItemValueRepository;

    @Resource
    private AttributeItemRepository attributeItemRepository;

    /**
     * 获取AttributeItem选项
     */
    private AttributeItemEntity getAttributeItem(Long attrItemId) {
        Check.notNull(attrItemId, "attrItemId 不能为空");
        AttributeItemEntity item = attributeItemRepository.selectByPrimaryKey(attrItemId);
        Check.notNull(item, "属性不存在 " + attrItemId);
        return item;
    }

    @Override
    public PageResult<AttributeItemValueListDTO> selectAttributeItemValuePageResult(AttributeItemValueQuery query) {
        PageResult<AttributeItemValueEntity> pageResult = attributeItemValueRepository.selectPageResult(query);
        return PageResult.of(pageResult, AttributeItemValueListDTO.class);
    }

    @Override
    public List<AttributeItemValueListDTO> selectAttributeItemValueList(AttributeItemValueQuery query) {
        List<AttributeItemValueEntity> list = attributeItemValueRepository.selectList(query);
        return Beans.copyList(list, AttributeItemValueListDTO.class);
    }

    @Override
    public AttributeItemValueDetailDTO getAttributeItemValueDetail(Long attrValueId) {
        Check.notNull(attrValueId, "attrValueId can not be null");
        AttributeItemValueEntity entity = attributeItemValueRepository.selectByPrimaryKey(attrValueId);
        return Beans.copy(entity, AttributeItemValueDetailDTO.class);
    }

    @Override
    public Long addAttributeItemValue(AttributeItemValueSaveDTO attributeItemValue) {
        final AttributeItemEntity attrItem = getAttributeItem(attributeItemValue.getAttrItemId());

        AttributeItemValueEntity entity = Beans.copy(attributeItemValue, AttributeItemValueEntity.class);
        entity.setAttrItemId(attrItem.getAttrItemId());
        entity.setAttrName(attrItem.getAttrName());
        entity.setCreateTime(Dates.getTimeNow());
        attributeItemValueRepository.insertSelective(entity);
        return entity.getAttrValueId();
    }

    @Override
    public Long editAttributeItemValue(AttributeItemValueUpdateDTO attributeItemValue) {
        Check.notNull(attributeItemValue.getAttrValueId(), "attrValueId can not be null");
        Check.notEmpty(attributeItemValue.getValueContent(), "SKU属性值不能为空");
        final AttributeItemEntity attrItem = getAttributeItem(attributeItemValue.getAttrItemId());

        AttributeItemValueEntity existEntity = attributeItemValueRepository.selectByPrimaryKey(attributeItemValue.getAttrValueId());
        Check.notNull(existEntity, "SKU属性值不存在");
        
        AttributeItemValueEntity updateEntity = Beans.copy(attributeItemValue, AttributeItemValueEntity.class);
        updateEntity.setAttrItemId(attrItem.getAttrItemId());
        updateEntity.setAttrName(attrItem.getAttrName());
        attributeItemValueRepository.updateByPrimaryKeySelective(updateEntity);
        return updateEntity.getAttrValueId();
    }

    @Override
    public void removeAttributeItemValue(Long attrValueId) {
        Check.notNull(attrValueId, "attrValueId can not be null");
        AttributeItemValueEntity entity = attributeItemValueRepository.selectByPrimaryKey(attrValueId);
        Check.notNull(entity, "SKU属性值不存在");
        attributeItemValueRepository.deleteByPrimaryKey(attrValueId);
    }

    @Override
    public List<AttributeItemValueListDTO> selectAttributeItemValueListByAttrId(Long attrId) {
        List<AttributeItemValueEntity> list = attributeItemValueRepository.selectListByAttrId(attrId);
        return Beans.copyList(list, AttributeItemValueListDTO.class);
    }

    @Override
    public List<AttributeItemCombineDTO> selectAttributeItemCombineList(Long categoryId) {
        Check.notNull(categoryId, "分类ID不能为空");

        AttributeItemQuery itemQuery = new AttributeItemQuery();
        itemQuery.setCategoryId(categoryId);
        List<AttributeItemEntity> attributeItemList = attributeItemRepository.selectList(itemQuery);

        // 查询属性值数据
        AttributeItemValueQuery query = new AttributeItemValueQuery();
        query.setCategoryId(categoryId);
        List<AttributeItemValueEntity> allValueList = attributeItemValueRepository.selectList(query);
        
        // 按照 attrItemId 分组
        Map<Long, List<AttributeItemValueEntity>> groupedMap = allValueList.stream()
                .collect(Collectors.groupingBy(
                        AttributeItemValueEntity::getAttrItemId,
                        LinkedHashMap::new,
                        Collectors.toList()
                ));
        
        // 构建组合信息列表，按照attributeItemList的sort顺序
        List<AttributeItemCombineDTO> resultList = new ArrayList<>();
        
        // 按照attributeItem的sort顺序遍历
        for (AttributeItemEntity attributeItem : attributeItemList) {
            Long attrItemId = attributeItem.getAttrItemId();
            List<AttributeItemValueEntity> valueList = groupedMap.get(attrItemId);
            
            if (valueList != null && !valueList.isEmpty()) {
                AttributeItemCombineDTO combineDTO = new AttributeItemCombineDTO();
                combineDTO.setAttrItemId(attrItemId);
                combineDTO.setAttrName(attributeItem.getAttrName()); // 使用attributeItem的属性名称
                
                // 构建属性值列表，按sort排序
                List<AttributeItemCombineDTO.AttributeValueInfo> attrValueList = valueList.stream()
                        .sorted((v1, v2) -> {
                            // 按sort字段升序排序，null值排在最后
                            if (v1.getSort() == null && v2.getSort() == null) return 0;
                            if (v1.getSort() == null) return 1;
                            if (v2.getSort() == null) return -1;
                            return v1.getSort().compareTo(v2.getSort());
                        })
                        .map(valueEntity -> {
                            AttributeItemCombineDTO.AttributeValueInfo valueInfo = 
                                    new AttributeItemCombineDTO.AttributeValueInfo();
                            valueInfo.setAttrValueId(valueEntity.getAttrValueId());
                            valueInfo.setValueContent(valueEntity.getValueContent());
                            return valueInfo;
                        })
                        .collect(Collectors.toList());
                
                combineDTO.setAttrValueList(attrValueList);
                resultList.add(combineDTO);
            }
        }
        
        return resultList;
    }
}
